package com.active.test.topic.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-11-26 下午12:55
 */
@Slf4j
public class JmsConsumer_Topic_Persist {
    private static final String ACTIVEMQ_URL = "tcp://localhost:61616";
    private static final String TOPIC_NAME = "topic-atguigu";

    /**
     * １．一定要先运行一次消费者，等于向ＭＱ注册，类似订阅了这个主题
     * ２．然后再运行生产者发送消息，此时
     * ３．无论消费者是否在线，都会接收到，不在线的话，下次连接的时候，会把没有收过的消息都接收下来
     *
     * @param args
     * @throws JMSException
     * @throws IOException
     */
    public static void main(String[] args) throws JMSException, IOException {
        log.info("我是3号消费者");

        //1.创建连接工厂，按照给定的url地址，采用默认用户名和密码
        final ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂，获取连接的connection
        final Connection connection = activeMQConnectionFactory.createConnection();
        connection.setClientID("z3");

        //3.创建会话session
        // 两个参数，第一个叫事务，第二个叫签收
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //4.创建目的地（具体是队列还是主题）
        final Topic topic = session.createTopic(TOPIC_NAME);
        final TopicSubscriber topicSubscriber = session.createDurableSubscriber(topic, "remark...");
        connection.start();

        Message message = topicSubscriber.receive();
        while (null != message) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("收到的持久化topic:" + ((TextMessage) message).getText());
            message = topicSubscriber.receive(1000L);
        }

        session.close();
        connection.close();
    }
}
